package com.controller.HdjConroller;

import com.Util.DB;
import com.Util.MailUtil;
import com.Util.SmsUtil;
import com.Util.serviceUtil.MD5;
import com.aliyuncs.exceptions.ClientException;
import com.commont.IpUtil;
import com.controller.BaseController;
import com.exception.JerseyException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.pojo.tables.HdjAuthCode;
import com.pojo.tables.records.HdjAuthCodeRecord;
import com.pojo.tables.records.HdjFlowRecord;
import com.pojo.tables.records.HdjIpRecord;
import com.pojo.tables.records.HdjUserRecord;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Random;

import static com.Util.UtilBase.*;

import static com.pojo.Tables.*;

import static com.Util.DBUtils.*;

/**
 * @Description:登录，注册专用
 * @Params:
 * @Return:
 * @Author: 王大军 @wangdajun
 * @Date: 2017/11/23 17:03
 * @Version 2.0
 */
@Path ( "user" )
public class loginController extends BaseController{


    /**
     * 获取验证码
     * @param create
     * @param phone
     * @param type
     * @return
     */
    public JsonObject getCode(DSLContext create,String phone,Integer code,Integer type){
        StringBuilder sql=new StringBuilder (  );
        sql.append(" SELECT \n");
        sql.append(" `code`.cellphone \n");
        sql.append(" from hdj_auth_code as `code` \n");
        sql.append(" where `code`.cellphone='"+phone+"'\n");
        sql.append(" and `code`.type='"+type+"' \n");
        sql.append(" and `code`.expiration_time>=unix_timestamp(now()) ");
        sql.append(" and `code`.sign_in_no='"+code+"' ");
        log.info ( "查询语句={}",sql.toString () );
        JsonObject result=dataChangeJsonObject ( create.fetchOne ( sql.toString () ) );
        return result;
    }

    /**
     * 判断用户是否存在
     * @param create
     * @param username
     * @param password
     * @return
     */
    public JsonObject login(DSLContext create,String username,String password){
        StringBuilder sql=new StringBuilder (  );
        sql.append(" SELECT \n");
        sql.append(" `user`.id,`user`.username,\n");
        sql.append(" `user`.phone ,\n");
        sql.append(" `user`.email ,\n");
        sql.append(" `user`.img_url AS `url`,\n");
        sql.append(" `user`.is_vip,FROM_UNIXTIME(`user`.vip_dated,'%Y-%m-%d %H:%i:%s') AS `time` \n");
        sql.append(" FROM hdj_user as `user` \n");
        sql.append(" WHERE (`user`.username='"+username+"' OR `user`.phone='"+username+"' OR `user`.email='"+username+"') \n");
        if (password!=null && password.length ()!=0 ) {
            sql.append ( " AND `user`.`password`='" + password + "' \n" );
        }
        log.info ( "【登录语句】={}",sql.toString () );
        JsonObject result=dataChangeJsonObject ( create.fetchOne ( sql.toString () ) );
        return result;
    }

    /**
     * 判断是否存在相同的用户
     * @param create
     * @param username
     * @param phone
     * @param email
     * @return
     */
    public JsonArray isExist(DSLContext create, String username, String email, String phone){
        StringBuilder sql=new StringBuilder (  );
        sql.append(" SELECT \n");
        sql.append(" `user`.id,`user`.username \n");
        sql.append(" FROM hdj_user as `user` \n");
        if (username!=null){
            sql.append(" WHERE `user`.username='"+username+"'\n");
        }
        if (email!=null){
            sql.append(" WHERE `user`.email='"+email+"'\n");
        }
        if (phone!=null){
            sql.append(" WHERE `user`.phone='"+phone+"'\n");
        }
        //log.info ( "【相同用户】={}",sql.toString () );
        JsonArray result=dataChangeJsonArray ( create.fetch ( sql.toString () ) );
        return result;
    }

    /**
     * 根据用户名查找用户的信息
     * @param create
     * @param username
     * @return
     */
    public JsonObject getUserByUsername(DSLContext create,String username){
        StringBuilder sql=new StringBuilder (  );
        sql.append(" SELECT \n");
        sql.append(" `user`.email,`user`.username,`user`.id,`user`.phone\n");
        sql.append(" FROM hdj_user AS `user` \n");
        sql.append(" WHERE `user`.username='"+username+"' \n");
        sql.append(" OR `user`.phone='"+username+"' \n");
        sql.append(" OR `user`.email='"+username+"' \n");
        return dataChangeJsonObject ( create.fetchOne ( sql.toString ()));
    }



    /**
     * 注册
     * @param query
     * @return
     */
    @POST
    @Path ( "register" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String register(String query){
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )){
            //读取参数
            JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ();

            String username=getJsonAsString ( jsonObject,"username" );
            String password=getJsonAsString ( jsonObject,"password" );
            String phone_number=getJsonAsString ( jsonObject,"phone_number" );
            Integer code=getJsonAsInt ( jsonObject,"code" );
            String email=getJsonAsString ( jsonObject,"email" );

            JsonObject result=getCode ( create,phone_number,code,1 );
            log.info ( "【code】={}",result );
            //判断验证码的正确定
            if (result==null||result.size ()==0 ){
                return error ( -1,"验证码正确，或者已经过期" );
            }
            JsonArray jsonObject1=isExist ( create,username,null,null);
            if (jsonObject1.size ()!=0){
                return error ( -1,"用户名已经存在" );
            }
            JsonArray jsonObject2=isExist ( create,null,email,null);
            if (jsonObject2.size ()!=0){
                return error ( -1,"邮箱已经存在" );
            }
            JsonArray jsonObject3=isExist ( create,null,null,phone_number);
            if (jsonObject3.size ()!=0){
                return error ( -1,"手机已经存在" );
            }

            //创建事务
            HdjUserRecord userRecord=create.newRecord ( HDJ_USER );
            create.transaction ( configuration -> {
                //执行新增操作
                userRecord.setEmail ( email );
                userRecord.setPassword ( MD5.md5 ( password ) );
                userRecord.setPhone ( phone_number );
                userRecord.setUsername ( username );
                userRecord.insert ();
                //发送欢迎邮件
                MailUtil.mailSend ( email,"欢迎注册后端军产品","" );
            } );
            return success (userRecord.getUsername ());
        }catch (Exception e){
            return error ( -1,e.getMessage () );
        }
    }

    /**
     * 登录
     * @param query
     * @return
     */
    @POST
    @Path ( "login" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String login(String query){
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )){
            //读取参数
            JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ();
            String username=getJsonAsString ( jsonObject,"username" );
            String password=getJsonAsString ( jsonObject,"password" );
            //判断登录
            JsonObject result=login ( create,username,MD5.md5 ( password ));
            if (result!=null && result.size ()!=0){
                //登录成功
                req.getSession ().setAttribute ( "login_user_id",getJsonAsString ( result,"id" ));
                return success (result);
            }
            return error ( -1,"用户名或者密码不正确" );
        }catch (Exception e){
            return error ( -1,e.getMessage () );
        }

    }

    /**
     * 发送短信
     * @param query
     * @return
     */
    @POST
    @Path ( "send_sms_email" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String sendSms(String query){
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )){
            JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ();
            String phone_or_email=getJsonAsString ( jsonObject,"phone_or_email" );
            Integer type=getJsonAsInt ( jsonObject,"type" );
            //生成随机6位数
            Integer code=new Random ().nextInt (999999);
            //设置验证码过期时间（15分钟）
            BigDecimal decimal=new BigDecimal ( "15" );
            BigDecimal decimal1=new BigDecimal ( "1000" );
            BigDecimal decimal2=new BigDecimal ( "60" );
            decimal=decimal.multiply ( decimal1 ).multiply ( decimal2 );
            //创建时间
            Long createTime=getCurrentTime ();
            //过期时间
            Long expirationTime=(getCurrentTime()*1000+decimal.longValue ())/1000;
            HdjAuthCodeRecord authCode=create.newRecord ( HDJ_AUTH_CODE );
            /*log.info ( "createTime={}",createTime );
            log.info ( "expirationTime={}",expirationTime );*/
            create.transaction ( configuration -> {
                //判断通过什么发送信息
                if(phone_or_email.indexOf ( "@" )!=-1){
                    MailUtil.mailSendCode ( phone_or_email,code);
                }else{
                    //手机发送
                    SmsUtil.sendSms ( phone_or_email,code.toString ());
                }

                //删除之前的记录
                create.delete ( HDJ_AUTH_CODE )
                        .where ( HDJ_AUTH_CODE.CELLPHONE.eq ( phone_or_email ) )
                        .and ( HDJ_AUTH_CODE.TYPE.eq ( type ) )
                        .execute ();
                //发送的短信入库处理
                authCode.setCellphone ( phone_or_email );
                authCode.setCreatetime ( createTime );
                authCode.setExpirationTime ( expirationTime );
                authCode.setSignInNo ( code.toString () );
                authCode.setType ( type );
                authCode.insert ();
            } );
        } catch (Exception e) {
                e.printStackTrace ();
            return error ( -1,e.getMessage () );
        }
        return success ("验证码发送成功");
    }


    /**
     * 获取当前登录的用户的信息
     * @return
     */
    @POST
    @Path ( "current_user" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String currentUser(){
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )){
            Integer userId=(Integer) req.getSession ().getAttribute ( "login_user_id" );
            if (userId!=null){
                Record result=create.select (  )
                        .from ( HDJ_USER )
                        .where ( HDJ_USER.ID.eq ( userId ) )
                        .fetchOne ();
                JsonObject jsonObject=dataChangeJsonObject ( result );
                return success (jsonObject);
            }
            return success ();
        }catch (Exception e){
            return error ( -1,e.getMessage () );
        }
    }

    /**
     *
     * @param query
     * @return
     */
    @POST
    @Path ( "is_exist" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String isExist(String query){
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )){
            JsonObject jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ();
            //获取参数
            String username=getJsonAsString ( jsonObject,"username");
            String email=getJsonAsString ( jsonObject,"email" );
            String phone=getJsonAsString ( jsonObject,"phone" );
           /* log.info ( "username={}",username );
            log.info ( "email={}",email );
            log.info ( "phone={}",phone );*/
            JsonArray result=isExist ( create,username,email,phone );

            if (result.size ()>0){
                //已经存在
                return error ( -1,"已经存在" );
            }
            return success ("可以使用");
        }catch (Exception e){
            return error ( -1,e.getMessage () );
        }
    }

    /**
     * 根据用户名查找用户
     * @param query
     * @return
     */
    @POST
    @Path ( "get_user_by_name" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String getUserByUserName(String query) {
        try (Connection conn = DB.getConnection ();
             DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )) {
            JsonObject jsonObject = new JsonParser ().parse ( query ).getAsJsonObject ();
            String username = getJsonAsString ( jsonObject, "username" );
            JsonObject result = getUserByUsername ( create, username );
            if (result.size () == 0) {
                return error ( -1, "用户名不存在" );
            }
            return success ( result );
        } catch (Exception e) {
            return error ( -1, e.getMessage () );
        }
    }

    /**
     * 验证验证码
     * @param query
     * @return
     */
    @POST
    @Path ( "auth_code" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String authCode(String query){
        try (Connection conn = DB.getConnection ();
             DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )) {
            JsonObject jsonObject = new JsonParser ().parse ( query ).getAsJsonObject ();
            Integer code = getJsonAsInt ( jsonObject, "code" );
            String param=getJsonAsString ( jsonObject,"param" );
            JsonObject result = getCode ( create,param,code,2 );
            if (result.size () == 0) {
                return error ( -1, "验证码不存在！或者过期" );
            }
            return success ( result );
        } catch (Exception e) {
            return error ( -1, e.getMessage () );
        }
    }

    /**
     * 修改密码
     * @param query
     * @return
     */
    @POST
    @Path ( "update_password" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String updatePassword(String query){
        try (Connection conn = DB.getConnection ();
             DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )) {
            JsonObject jsonObject = new JsonParser ().parse ( query ).getAsJsonObject ();
            Integer id = getJsonAsInt ( jsonObject, "id" );
            String password=getJsonAsString ( jsonObject,"password" );
            HdjUserRecord userRecord=create.newRecord ( HDJ_USER );
            userRecord.setId ( id );
            userRecord.setPassword ( MD5.md5 ( password ) );
            Integer result=userRecord.update ();
            if (result==0){
                return error ( -1,"修改失败!请联系管理员" );
            }
            return success ( );
        } catch (Exception e) {
            return error ( -1, e.getMessage () );
        }
    }


    /**
     * 获取历史访问的人数
     * @return
     */
    @POST
    @Path ( "get_flow" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String getFlow(){
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )){
            //先获取当前访问的ip
            String ip= IpUtil.getIpAddr ( req );
            //判断此ip是否存在
            Record ipRecord=create.fetchOne ("SELECT * FROM hdj_ip WHERE ip='"+ip+"'");
            this.jsonObject=dataChangeJsonObject ( ipRecord );
            if (this.jsonObject.size ()>0){
                this.jsonObject=dataChangeJsonObject ( create.fetchOne ( "SELECT * FROM hdj_flow " ) );
                return success (this.jsonObject);
            }
            //ip入库
            HdjIpRecord hdjIpRecord=create.newRecord ( HDJ_IP );
            hdjIpRecord.setIp ( ip );
            hdjIpRecord.insert ();
            //开始计算总数入库并返回
            HdjFlowRecord flowRecord=create.select (  )
                    .from ( HDJ_FLOW )
                    .where ( HDJ_FLOW.ID.eq ( 1 ) )
                    .fetchOne ()
                    .into ( HdjFlowRecord.class );
            HdjFlowRecord hdjFlowRecord=create.newRecord ( HDJ_FLOW );
            hdjFlowRecord.setId ( 1 );
            hdjFlowRecord.setToday (flowRecord.getToday ()+1 );
            hdjFlowRecord.setHistory ( flowRecord.getHistory ()+1 );
            hdjFlowRecord.update ();
            //查询总数
            this.jsonObject=dataChangeJsonObject ( create.fetchOne ( "SELECT * FROM hdj_flow " ) );
        }catch (Exception e){
            //e.printStackTrace ();
            return error (-1,e.getMessage ());
        }
        return success ( this.jsonObject);
    }


    /**
     * 修改用户的信息
     * @param query
     * @return
     */

    @POST
    @Path ( "update_info" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String updateInfo(String query){
        try(Connection conn = DB.getConnection ();
            DSLContext create = DSL.using ( conn, SQLDialect.MYSQL )) {
            JsonObject json=new JsonParser ().parse ( query ).getAsJsonObject ();
            String imgUrl=getJsonAsString ( json,"imgUrl" );
            String userName=getJsonAsString ( json,"userName" );
            String phone=getJsonAsString ( json,"phone" );
            String email=getJsonAsString ( json,"email" );
            Integer userId=getJsonAsInt ( json,"userId" );
            create.transaction ( configuration -> {
                //判断手机和email是否可用（自己除外）
                StringBuilder sql=new StringBuilder ( "SELECT id FROM hdj_user hd WHERE hd.phone='"+phone+"' AND hd.id!="+userId+" LIMIT 1" );
                JsonObject jsonObject1=dataChangeJsonObject ( create.fetchOne ( sql.toString () ) );
                if (jsonObject1.size ()!=0){
                    throw new JerseyException ( "此手机已经存在" );
                }
                //判断用户名
                sql=new StringBuilder ( "SELECT id FROM hdj_user hd WHERE hd.username='"+userName+"' AND hd.id!="+userId+" LIMIT 1" );
                JsonObject jsonObject2=dataChangeJsonObject ( create.fetchOne ( sql.toString () ) );
                if (jsonObject2.size ()!=0){
                    throw new JerseyException ( "此用户名已经存在" );
                }
                //判断手机
                sql=new StringBuilder ( "SELECT id FROM hdj_user hd WHERE hd.email='"+userName+"' AND hd.id!="+userId+" LIMIT 1" );
                JsonObject jsonObject3=dataChangeJsonObject ( create.fetchOne ( sql.toString () ) );
                if (jsonObject3.size ()!=0){
                    throw new JerseyException ( "此邮箱已经存在" );
                }
                //执行修改
                HdjUserRecord hdjUserRecord=create.newRecord ( HDJ_USER );
                hdjUserRecord.setId ( userId );
                hdjUserRecord.setUsername ( userName );
                hdjUserRecord.setPhone ( phone );
                hdjUserRecord.setEmail ( email );
                hdjUserRecord.setImgUrl ( imgUrl );
                hdjUserRecord.update ();
            } );
            return success ();
        }catch (Exception e){
            return error (-1,e.getMessage ());
        }
    }









}
